import {app, BrowserWindow, dialog, ipcMain, shell} from 'electron'
import '../renderer/store'
import {aria2cPort} from "../renderer/config";

const {startHttpServer} = require('./httpService'); // 引入服务模块
const {exec, execSync} = require('child_process');
const path = require('path');
const os = require('os');
const fs = require('fs');
const iconv = require('iconv-lite');
const net = require('net')
/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
    global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
let aria2Process
const isDev = process.env.NODE_ENV === 'development'
const winURL = isDev
    ? `http://localhost:9080`
    : `file://${__dirname}/index.html`

 function createWindow() {
    /**
     * Initial window options
     */
    mainWindow = new BrowserWindow({
        height: isDev ? 563 : 650,
        useContentSize: true,
        width: isDev ? 1000 : 750,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,  // 确保你能够使用 node 模块
            enableRemoteModule: true
        }
    })

    mainWindow.loadURL(winURL)

    mainWindow.on('closed', () => {
        mainWindow = null
    })
    // 启动 HTTP 服务并传入主窗口对象
    startHttpServer(mainWindow);

}

//清除aria2进程
function killAria2Processes() {
    return new Promise((resolve, reject) => {
        exec('taskkill /F /IM aria2c_64.exe', (err, stdout, stderr) => {
            if (err) {
                console.error('无法终止 aria2 进程:', err);
            }
            resolve(err)
            console.log('成功终止所有 aria2 进程');
            console.log(stdout);
        });
    })
}

async function startAria2() {
    await killAria2Processes()
    // 使用 path.join 获取可执行文件路径
    const execFilePath =
        process.env.NODE_ENV === 'production' ?
            path.join(process.resourcesPath, '/aria2c/aria2c_64.exe')
            :
            path.join(__dirname, '../renderer/aria2/.aria2/aria2c_64.exe'); // 使用相对路径引用
    // C:\Users\哇咔咔\AppData\Local\Temp\2jPRyvunecmRdeJpQNZEfNjEDjC\resources\aria2c
    // const execFilePath = path.resolve('C:\\','./Users/59717/AppData/Local/Temp/2jPRyvunecmRdeJpQNZEfNjEDjC/resources/aria2c/aria2c_64.exe'); // 使用相对路径引用
    // console.log("execFilePath1",execFilePath)
    // const commandBuffer = iconv.decode(Buffer.from(execFilePath, 'binary'), 'utf-8')
    // console.log("commandBuffer",commandBuffer)
    console.log("execFilePath", execFilePath)
    aria2Process = exec(`${execFilePath} --enable-rpc --rpc-listen-port=${aria2cPort} --rpc-allow-origin-all`, (error, stdout, stderr) => {
        if (error) {
            console.error(`Error starting aria2: ${error}`);
            return;
        }
        console.log(`aria2 output: ${stdout}`);
        if (stderr) {
            console.error(`aria2 stderr: ${stderr}`);
        }
    });
    fs.writeFileSync('aria2Process.pid', aria2Process.pid.toString());
    aria2Process.on('exit', (code, signal) => {
        console.log(`aria2 进程  process exited with code ${code} and signal ${signal}`);
    });
}

//清除进程
function clearProcess() {
    if (aria2Process) {
        if (os.platform() === 'win32') {
            console.log("aria2Process.pid", aria2Process.pid)
            console.log("taskkill", `taskkill /pid ${aria2Process.pid} /T /F`)
            try {
                execSync(`taskkill /F /IM aria2c_64.exe`);
            } catch (e) {
                console.log("e", e)
            }

        } else {
            aria2Process.kill('SIGKILL');
            aria2Process = null;
            console.log('aria2 进程已终止');
        }
        fs.unlinkSync('aria2Process.pid')
    }
    //从文件中读取 express 进程的 PID
    const expressPid = fs.readFileSync('express.pid', 'utf8');
    console.log("expressPid", expressPid)
    if (expressPid) {
        execSync(`taskkill /pid ${expressPid} /T /F`);
        fs.unlinkSync('express.pid')
    }
}


function checkPortInUseSync(port) {
    return new Promise((resolve, reject) => {
        const server = net.createServer()

        server.once('error', function (err) {
            if (err.code === 'EADDRINUSE') {
                resolve(true)  // 端口被占用
            } else {
                reject(err)
            }
        })

        server.once('listening', function () {
            server.close()
            resolve(false)  // 端口未被占用
        })

        server.listen(port)
    })
}
app.on('ready', async () => {
    const isInUse = await checkPortInUseSync(16600)
    if (isInUse) {
        console.log('Port 16600 is in use. Exiting...')
        app.quit()  // 退出应用程序
    } else {
        console.log('Port 16600 is available. Proceeding with window creation.')
        // await startAria2();
        createWindow()
    }
})

app.on('window-all-closed', () => {
    console.log("window-all-closed执行")
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('before-quit', () => {
    console.log("before-quit执行")
    // console.log("aria2Process", aria2Process.pid)
    // clearProcess()
});

app.on('quit', () => {
    // clearProcess()
});

app.on('activate', () => {
    if (mainWindow === null) {
        createWindow()
    }
})

// 处理文件夹选择对话框
ipcMain.on('show-folder-dialog', async (event) => {
    const result = await dialog.showOpenDialog(mainWindow, {
        properties: ['openDirectory']
    });
    event.sender.send('selected-folder', result); // 返回选择的文件夹路径
});

// 处理打开文件夹对话框请求
ipcMain.on('open-folder', (event, folderPath) => {
    console.log("folderPath", folderPath)
    shell.openExternal(folderPath); // 使用 shell.openPath 打开文件夹
});

ipcMain.on('get-desktop-path', (event) => {
    const desktopPath = path.join(os.homedir(), 'Desktop');
    console.log("desktopPath----", desktopPath)

    event.sender.send('get-desktop-path', desktopPath);
});

ipcMain.on('get-mac-address', (event) => {
    const networkInterfaces = os.networkInterfaces();
    let macAddress = '';

    for (const key in networkInterfaces) {
        networkInterfaces[key].forEach(iface => {
            if (iface.mac && iface.mac !== '00:00:00:00:00:00' && !macAddress) {
                macAddress = iface.mac;
            }
        });
        if (macAddress) break;
    }
    event.sender.send('get-mac-address', macAddress);
});

// 监听打开网址的请求
ipcMain.on('open-url', (event, url) => {
    shell.openExternal(url);
});
/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
